package com.lxmes.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.*;
public class BaiDuTranslate {
    public static final String API_KEY = "yTWziJXbSWejeDWlbN4rpdtO";
    public static final String SECRET_KEY = "VnsXLgPHG2VzGOhK7OybXaax6a7VPGwl";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getTranslate(String zhName){
        String result ="";
        try {
            MediaType mediaType = MediaType.parse("application/json");
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("from","zh");
            jsonObject.put("to","en");
            jsonObject.put("q",zhName);
            RequestBody body = RequestBody.create(mediaType, jsonObject.toJSONString());
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            JSONObject JSONObjectResult = JSON.parseObject(response.body().string());
            result = JSONObjectResult.getJSONObject("result").getJSONArray("trans_result").getJSONObject(0).getString("dst");
        }catch (Exception e){
            e.printStackTrace();
        }
        //System.out.println(result);
        return result;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string()).getString("access_token");
    }
}
